#include "mainwindow.h"
#include <QPainter>
#include <QPainterPath>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    this->resize(800, 600);
    m_curve_render = new BarrierCurveRender();
}

MainWindow::~MainWindow() {
    delete m_curve_render;
}

void MainWindow::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    QPainter painter(this);
    painter.setPen(Qt::white);
    painter.setBrush(Qt::white);
    painter.drawRect(0,0,800,600);


    int sampleCnt = m_curve_render->getMiddleSampleSize();

    // draw middle curve
    for (int i = 0; i < sampleCnt; i++) {
        int px,py;

        // middle
        painter.setPen(Qt::red);
        painter.setBrush(Qt::red);

        px = m_curve_render->getMiddleSample(i).x();
        py = m_curve_render->getMiddleSample(i).y();
        painter.drawEllipse(QPoint(px, py), 2, 2);

        // left
        painter.setPen(Qt::green);
        painter.setBrush(Qt::green);

        px = m_curve_render->getLeftSample(i).x();
        py = m_curve_render->getLeftSample(i).y();
        painter.drawEllipse(QPoint(px, py), 2, 2);

        // right
        painter.setPen(Qt::blue);
        painter.setBrush(Qt::blue);

        px = m_curve_render->getRightSample(i).x();
        py = m_curve_render->getRightSample(i).y();
        painter.drawEllipse(QPoint(px, py), 2, 2);
    }

    QPen pen;
    pen.setColor(Qt::black);
    pen.setWidth(1);
    painter.setPen(pen);
    painter.setBrush(Qt::NoBrush);

    QPainterPath path;
    for (int i = 0; i < m_curve_render->ebo_size; i+= 3) {
        path.clear();
        path.moveTo( getPointFromEbo(i));
        path.lineTo( getPointFromEbo(i + 1));
        path.lineTo( getPointFromEbo(i + 2));
        path.closeSubpath();
        painter.drawPath(path);
    }

}

QPoint MainWindow::getPointFromEbo(int ebo_index)
{
    std::shared_ptr<float> ptr_vertex_buffer = m_curve_render->ptr_vertex_buffer;
    std::shared_ptr<unsigned int> ptr_index_buffer = m_curve_render->ptr_index_buffer;

    QPoint p;
    unsigned int index = ptr_index_buffer.get()[ebo_index];
    p.setX( ptr_vertex_buffer.get()[index * 3]);
    p.setY( ptr_vertex_buffer.get()[index * 3 + 1]);

    return p;
}











